<template>
  <div>
    <div class="search-suggestion">
      <van-cell 
          v-for="(item,index) in suggestions"
          :key="index"
          icon="search"
          @click="$emit('search',item)"
      >
      <div slot="title" v-html="highlight(item)"></div>
    </van-cell>

      
    </div>
  </div>
</template>

<script>
import {getSearchSuggest} from '@/api/search'
//防抖引入
import {debounce} from 'lodash'
export default {
    name:'SearchSuggestion',
    props:{
      search_text:{
          type:String,
          reuquired:true
      }
    },
    data() {
      return {
        suggestions:[], //匹配结果
        htmlStr: 'Hello <span style="color: red">World</span>'
      }
    },
    watch:{
      search_text:{
        //当search_text发生改变调用handler函数
        //  handler(value){
        //   this.loadSearchSuggestions(value)
        // },
        handler:debounce(function(value){
          this.loadSearchSuggestions(value)
        },200),
        immediate:true
      }
    },
    methods:{
      async loadSearchSuggestions(q){
          try{
            const {data} = await getSearchSuggest(q)
            this.suggestions = data.data.options
          }catch(err){
            this.$toast('数据获取失败，请稍后重试！')
          }
      },
      highlight(val){
        const highlightStr = `<span class="activeText">${this.search_text}</span>`
        //RegExp 正则表达式构造函数
        /*
          参数1：匹配字符串
          参数2：匹配模式
        */
        const reg = new RegExp(this.search_text,'gi')
        return val.replace(reg,highlightStr)
      }
    }
}
</script>

<style lang="less" scoped>
  .search-suggestion{
    /deep/span.activeText{
      color: #3296fa !important;
    }
  }
</style>